<template>
  <div class="order-form">
    <div class="page-header">
      <h2>创建订单</h2>
    </div>
    
    <el-steps :active="activeStep" finish-status="success" simple style="margin-bottom: 30px">
      <el-step title="选择客户"></el-step>
      <el-step title="添加商品"></el-step>
      <el-step title="确认订单"></el-step>
    </el-steps>
    
    <!-- 第一步：选择客户 -->
    <div v-show="activeStep === 0">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>选择客户</span>
          <el-button style="float: right;" type="text" @click="showAddCustomerDialog">添加新客户</el-button>
        </div>
        
        <div class="search-bar">
          <el-input
            v-model="customerSearch"
            placeholder="输入客户姓名或邮箱搜索"
            @input="searchCustomers"
            clearable
            style="width: 300px;">
          </el-input>
        </div>
        
        <el-table
          v-loading="customerLoading"
          :data="filteredCustomers"
          border
          style="width: 100%"
          highlight-current-row
          @current-change="handleCustomerSelect">
          <el-table-column
            prop="customerId"
            label="客户ID"
            width="80">
          </el-table-column>
          <el-table-column
            prop="name"
            label="客户名称"
            width="150">
          </el-table-column>
          <el-table-column
            prop="email"
            label="电子邮箱"
            width="200">
          </el-table-column>
          <el-table-column
            prop="phone"
            label="联系电话"
            width="150">
          </el-table-column>
          <el-table-column
            prop="address"
            label="联系地址">
          </el-table-column>
          <el-table-column
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="success"
                @click="selectCustomer(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="form-footer">
          <el-button @click="$router.push('/orders')">取消</el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 第二步：添加商品 -->
    <div v-show="activeStep === 1">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>添加商品</span>
        </div>
        
        <div class="search-bar">
          <el-input
            v-model="productSearch"
            placeholder="输入商品名称搜索"
            @input="searchProducts"
            clearable
            style="width: 300px;">
          </el-input>
        </div>
        
        <el-table
          v-loading="productLoading"
          :data="filteredProducts"
          border
          style="width: 100%">
          <el-table-column
            prop="productId"
            label="商品ID"
            width="80">
          </el-table-column>
          <el-table-column
            prop="name"
            label="商品名称"
            width="200">
          </el-table-column>
          <el-table-column
            prop="description"
            label="商品描述">
          </el-table-column>
          <el-table-column
            prop="price"
            label="单价"
            width="100">
            <template slot-scope="scope">
              {{ scope.row.price }} 元
            </template>
          </el-table-column>
          <el-table-column
            prop="stock"
            label="库存"
            width="80">
          </el-table-column>
          <el-table-column
            label="操作"
            width="180">
            <template slot-scope="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                :max="scope.row.stock"
                size="mini"
                style="width: 90px;"
                controls-position="right">
              </el-input-number>
              <el-button
                size="mini"
                type="primary"
                @click="addToCart(scope.row)"
                :disabled="!scope.row.quantity || scope.row.quantity <= 0">
                添加
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <h3 style="margin-top: 20px;">已选商品</h3>
        <el-table
          :data="cart"
          border
          style="width: 100%">
          <el-table-column
            prop="productId"
            label="商品ID"
            width="80">
          </el-table-column>
          <el-table-column
            prop="name"
            label="商品名称"
            width="200">
          </el-table-column>
          <el-table-column
            prop="price"
            label="单价"
            width="200">
            <template slot-scope="scope">
              {{ scope.row.price }} 元
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="数量"
            width="200">
          </el-table-column>
          <el-table-column
            label="小计"
            width="240">
            <template slot-scope="scope">
              {{ (scope.row.price * scope.row.quantity).toFixed(2) }} 元
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="removeFromCart(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="form-footer">
          <el-button @click="activeStep = 0">上一步</el-button>
          <el-button type="primary" @click="goToConfirm" :disabled="cart.length === 0">下一步</el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 第三步：确认订单 -->
    <div v-show="activeStep === 2">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>确认订单</span>
        </div>
        
        <h3>客户信息</h3>
        <div class="info-block" v-if="selectedCustomer">
          <div class="info-item">
            <span class="label">客户名称:</span>
            <span class="value">{{ selectedCustomer.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话:</span>
            <span class="value">{{ selectedCustomer.phone || '无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">电子邮箱:</span>
            <span class="value">{{ selectedCustomer.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系地址:</span>
            <span class="value">{{ selectedCustomer.address || '无' }}</span>
          </div>
        </div>
        
        <h3 style="margin-top: 20px;">订单商品</h3>
        <el-table
          :data="cart"
          border
          style="width: 100%">
          <el-table-column
            prop="name"
            label="商品名称"
            width="200">
          </el-table-column>
          <el-table-column
            prop="price"
            label="单价"
            width="100">
            <template slot-scope="scope">
              {{ scope.row.price }} 元
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="数量"
            width="100">
          </el-table-column>
          <el-table-column
            label="小计"
            width="120">
            <template slot-scope="scope">
              {{ (scope.row.price * scope.row.quantity).toFixed(2) }} 元
            </template>
          </el-table-column>
        </el-table>
        
        <div class="order-summary">
          <div class="total">订单总金额: <span class="amount">{{ totalAmount.toFixed(2) }}</span> 元</div>
        </div>
        
        <div class="form-footer">
          <el-button @click="activeStep = 1">上一步</el-button>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 添加客户对话框 -->
    <el-dialog title="添加客户" :visible.sync="customerDialogVisible" width="500px">
      <el-form :model="customerForm" :rules="customerRules" ref="customerForm" label-width="100px">
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="customerForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="customerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="customerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="联系地址" prop="address">
          <el-input type="textarea" v-model="customerForm.address" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="customerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCustomerForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import customerApi from '@/api/customer'
import productApi from '@/api/product'
import orderApi from '@/api/order'

export default {
  name: 'OrderForm',
  
  data() {
    return {
      activeStep: 0,
      customerLoading: true,
      productLoading: true,
      customers: [],
      products: [],
      customerSearch: '',
      productSearch: '',
      selectedCustomer: null,
      cart: [],
      customerDialogVisible: false,
      customerForm: {
        name: '',
        email: '',
        phone: '',
        address: ''
      },
      customerRules: {
        name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ]
      }
    }
  },
  
  computed: {
    filteredCustomers() {
      return this.customers.filter(customer => {
        const search = this.customerSearch.toLowerCase()
        return !search ||
          customer.name.toLowerCase().includes(search) ||
          (customer.email && customer.email.toLowerCase().includes(search))
      })
    },
    
    filteredProducts() {
      return this.products.filter(product => {
        const search = this.productSearch.toLowerCase()
        return !search ||
          product.name.toLowerCase().includes(search) ||
          (product.description && product.description.toLowerCase().includes(search))
      }).map(product => {
        // 添加数量字段
        return {
          ...product,
          quantity: 1
        }
      })
    },
    
    totalAmount() {
      return this.cart.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    }
  },
  
  created() {
    this.fetchCustomers()
    this.fetchProducts()
  },
  
  methods: {
    // 获取客户列表
    async fetchCustomers() {
      this.customerLoading = true
      try {
        const response = await customerApi.getAllCustomers()
        this.customers = response.data
        this.customerLoading = false
      } catch (error) {
        this.$message.error('获取客户列表失败')
        this.customerLoading = false
      }
    },
    
    // 获取商品列表
    async fetchProducts() {
      this.productLoading = true
      try {
        const response = await productApi.getAllProducts()
        this.products = response.data.filter(product => product.stock > 0)
        this.productLoading = false
      } catch (error) {
        this.$message.error('获取商品列表失败')
        this.productLoading = false
      }
    },
    
    // 搜索客户
    searchCustomers() {
      // 前端过滤，无需发送请求
    },
    
    // 搜索商品
    searchProducts() {
      // 前端过滤，无需发送请求
    },
    
    // 选择客户
    selectCustomer(customer) {
      this.selectedCustomer = customer
      this.activeStep = 1
    },
    
    // 处理客户选择
    handleCustomerSelect(row) {
      if (row) {
        this.selectedCustomer = row
      }
    },
    
    // 显示添加客户对话框
    showAddCustomerDialog() {
      this.customerDialogVisible = true
      this.customerForm = {
        name: '',
        email: '',
        phone: '',
        address: ''
      }
    },
    
    // 提交客户表单
    async submitCustomerForm() {
      this.$refs.customerForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await customerApi.addCustomer(this.customerForm)
            if (response.data.success) {
              this.$message.success(response.data.message)
              this.customerDialogVisible = false
              
              // 重新获取客户列表
              await this.fetchCustomers()
              
              // 选择新添加的客户
              const newCustomer = this.customers.find(c => c.customerId === response.data.customerId)
              if (newCustomer) {
                this.selectCustomer(newCustomer)
              }
            } else {
              this.$message.error(response.data.message)
            }
          } catch (error) {
            this.$message.error('添加客户失败')
          }
        } else {
          return false
        }
      })
    },
    
    // 添加商品到购物车
    addToCart(product) {
      // 检查是否已在购物车中
      const existingIndex = this.cart.findIndex(item => item.productId === product.productId)
      
      if (existingIndex >= 0) {
        // 更新数量
        const newQuantity = this.cart[existingIndex].quantity + product.quantity
        
        // 检查库存
        if (newQuantity <= product.stock) {
          this.cart[existingIndex].quantity = newQuantity
          this.$message.success('已更新商品数量')
        } else {
          this.$message.warning('超出可用库存')
        }
      } else {
        // 添加新商品
        this.cart.push({
          productId: product.productId,
          name: product.name,
          price: product.price,
          quantity: product.quantity,
          stock: product.stock
        })
        this.$message.success('已添加商品到订单')
      }
    },
    
    // 从购物车移除商品
    removeFromCart(index) {
      this.cart.splice(index, 1)
      this.$message.success('已移除商品')
    },
    
    // 进入确认页面
    goToConfirm() {
      if (this.cart.length > 0) {
        this.activeStep = 2
      } else {
        this.$message.warning('请先选择商品')
      }
    },
    
    // 提交订单
    async submitOrder() {
      if (!this.selectedCustomer) {
        this.$message.error('请选择客户')
        this.activeStep = 0
        return
      }
      
      if (this.cart.length === 0) {
        this.$message.error('请选择商品')
        this.activeStep = 1
        return
      }
      
      try {
        // 构建订单数据
        const orderData = {
          customerId: this.selectedCustomer.customerId,
          totalAmount: this.totalAmount,
          status: 'pending',
          items: this.cart.map(item => ({
            productId: item.productId,
            quantity: item.quantity,
            unitPrice: item.price
          }))
        }
        
        const response = await orderApi.createOrder(orderData)
        
        if (response.data.success) {
          this.$message.success(response.data.message)
          // 转到订单详情页
          this.$router.push(`/orders/${response.data.orderId}`)
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('创建订单失败')
      }
    }
  }
}
</script>

<style scoped>
.order-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.form-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.info-block {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.label {
  width: 100px;
  color: #606266;
}

.value {
  color: #303133;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
}

.total {
  font-weight: bold;
  color: #606266;
}

.amount {
  color: #f56c6c;
  font-size: 20px;
}
</style> 